<template>
  <!-- 搜索表单 -->
  <el-form ref="formRef" :model="model" label-width="100px" :inline="true">
    <!-- 始终显示的表单项 -->

    <!-- 动态显示的表单项 -->
    <template v-for="(item, index) in visibleItems" :key="index">
      <component :is="item" v-show="shouldShow(index)" />
    </template>

    <!-- 操作按钮 -->
    <el-form-item style="margin-left: 30px">
      <el-button type="primary" @click="handleSearch">
        <template #icon><ep-Search /></template>
        搜索
      </el-button>
      <el-button @click="handleReset">
        <template #icon><ep-Refresh /></template>
        重置
      </el-button>
      <el-button type="primary" link @click="handleCollapsedChange">
        {{ isCollapsed ? '展开' : '收起' }}
        <el-icon :class="{ 'rotate-icon': !isCollapsed }">
          <ep-ArrowDown />
        </el-icon>
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'

interface Props {
  model: Record<string, any> // 表单数据
  showNumber?: number
  defaultCollapsed?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  showNumber: 4,
  defaultCollapsed: true
})

const emit = defineEmits<{
  (e: 'search'): void
  (e: 'reset'): void
  (e: 'collapsedChange', value: boolean): void
}>()

const slots = useSlots()

const formRef = ref<FormInstance>()

// 折叠状态
const isCollapsed = ref(props.defaultCollapsed)

// 获取插槽内容
const slotItems = computed<VNode[]>(() => {
  return slots.default?.() || []
})

// 计算可见的表单项
// const visibleItems = computed(() => {
//   return isCollapsed.value ? slotItems.value.slice(0, props.showNumber) : slotItems.value
// })

const visibleItems = computed(() => {
  return slotItems.value
})

// 判断是否显示
const shouldShow = (index: number) => {
  return isCollapsed.value ? index < props.showNumber : true
}

// 搜索方法
const handleSearch = () => {
  emit('search')
}

// 重置方法
const handleReset = () => {
  emit('reset')
}

const handleCollapsedChange = () => {
  isCollapsed.value = !isCollapsed.value
  emit('collapsedChange', isCollapsed.value)
}

const resetFields = () => {
  formRef.value.resetFields()
}

defineExpose({
  resetFields
})
</script>

<style scoped>
.rotate-icon {
  transform: rotate(180deg);
  transition: transform 0.3s;
}
</style>
